<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
class UserController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth')->except('login');
    }

    public function login(Request $request)
    {
        $config = [
            'app_id' => config('WeChat.app_id'),
            'secret' => config('WeChat.secret'),
        ];

        $app = Factory::miniProgram($config);

        $validata =Validator::make($request->all(), [
            'code' => 'required',
            'iv' => 'required',
            'encryptedData' => 'required',
            'signature' => 'required',
        ]);
        if ($validata->fails()) {
            return ajax(402,'参数错误',$validata->errors()->first());
        }

         $session_key = $app->auth->session($request->code);
         if (isset($session_key['errcode'])){
                return ajax(0,'登录失败',$session_key['errcode']);
         }
         $wx = new \WXBizDataCrypt($config['app_id'],$session_key['session_key']);
         $errCode = $wx->decryptData($request->encryptedData,$request->iv,$data);
         $data = json_decode($data,true);
         if ($errCode == 0){
             $model = new User();
             $user = $model->where('open_id',$session_key['openid'])->value('id');
             //判断用户是否存在
             if (empty($user)) {
                 //用户不存在
                 $model->nickname = $data['nickName'];
                 $model->gender = $data['gender'];
                 $model->avatar = $data['avatarUrl'];
                 $model->open_id = $data['openId'];
                 $model->api_token = hash('sha256',Str::random(60));
                 $model->expire_time = strtotime('+3 hours');
                 $res = $model->save();
                 if ($res) {
                     $json = ajax(201, '登录成功',$model);
                 } else {
                     $json = ajax(202, '登录失败');
                 }
                 return $json;
             }else{
                 //用户存在
                 $field = [
                     'api_token'=>hash('sha256',Str::random(60)),
                     'expire_time'=>strtotime('+3 hours'),
                     'updated_at'=>time()
                 ];
                 $res = User::where('open_id',$data['openId'])->update($field);
                 $userdata = User::where('open_id',$data['openId'])->first();
                 if ($res && $userdata) {
                     $json = ajax(200, '登录成功',$userdata);
                 } else {
                     $json = ajax(202, '登录失败');
                 }
                 return $json;
             }

         }else{
             return ajax(0,'登录失败');
         }



    }
}
